package com.egg.ylt.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.egg.ylt.R;
import com.egg.ylt.Utils.Constants;
import com.egg.ylt.Utils.StringUtil;
import com.egg.ylt.activity.ACT_AddGrowRecord;
import com.egg.ylt.adapter.ADA_GrowUpRecord;
import com.egg.ylt.pojo.GrowUpRecordEntity;
import com.egg.ylt.presenter.impl.GrowRecordPresenterImpl;
import com.egg.ylt.view.IGrowRecordView;
import com.jcodecraeer.xrecyclerview.ArrowRefreshHeader;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.yonyou.framework.library.base.BaseFragment;
import com.yonyou.framework.library.bean.ErrorBean;
import com.yonyou.framework.library.common.utils.BitmapUtil;
import com.yonyou.framework.library.common.utils.ListUtil;
import com.yonyou.framework.library.common.utils.ScreenUtil;
import com.yonyou.framework.library.common.utils.ToastUtil;
import com.yonyou.framework.library.dialog.AlertDialog;
import com.yonyou.framework.library.eventbus.EventCenter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import androidx.annotation.NonNull;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by lijiateng on 2019/1/19.
 */

public class FRA_GrowUpRecord extends BaseFragment<GrowRecordPresenterImpl> implements IGrowRecordView, XRecyclerView.LoadingListener {

    public static final String KEY_BABY_ID = "key_baby_id";

    @BindView(R.id.fl_root)
    FrameLayout flRoot;
    @BindView(R.id.ll_record_empty)
    LinearLayout llRecordEmpty;
    @BindView(R.id.rv_record)
    XRecyclerView rvRecord;

    private int mCurrPage = 1;

    private ADA_GrowUpRecord recordAdapter;

    private AlertDialog modifyItemDialog;
    private int modifyItemPos = -1;

    private String babyId;

    @Override
    public void showBusinessError(ErrorBean error) {

    }

    @Override
    public void showError(String msg) {
        ToastUtil.makeText(mContext, msg, false);
    }

    @Override
    protected void onFirstUserVisible() {

    }

    @Override
    protected void onUserVisible() {

    }

    @Override
    protected void onUserInvisible() {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (!hidden) {
            onRefresh();
        }

    }

    @Override
    protected View getLoadingTargetView() {
        return flRoot;
    }

    @Override
    protected void initViewsAndEvents() {

        // 获取宝宝 id
        babyId = getArguments().getString(KEY_BABY_ID);

        recordAdapter = new ADA_GrowUpRecord(mContext);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        rvRecord.setLayoutManager(linearLayoutManager);
        rvRecord.setAdapter(recordAdapter);

        rvRecord.setPullRefreshEnabled(true);
        rvRecord.setLoadingMoreEnabled(true);
        rvRecord.setLoadingListener(this);

//        mPresenter.getGrowUpRecordList(babyId, mCurrPage);

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fra_grow_up_record;
    }

    @Override
    protected void onEventComming(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case Constants.MODIFY_RECORD_EVENT:
                GrowUpRecordEntity.ListBean recordEntity = (GrowUpRecordEntity.ListBean) eventCenter.getData();
                showAlertToModifyItem(recordEntity);
                modifyItemPos = recordEntity.getPosition();
                break;
        }
    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    public static FRA_GrowUpRecord newInstance(@NonNull String babyId) {
        FRA_GrowUpRecord fragment = new FRA_GrowUpRecord();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_BABY_ID, babyId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void updateGrowRecordList(List<GrowUpRecordEntity.ListBean> list) {

        rvRecord.refreshComplete();
        rvRecord.loadMoreComplete();

        // 空数据集，展示空页面
        if (ListUtil.isListEmpty(list) && mCurrPage == 1) {
            llRecordEmpty.setVisibility(View.VISIBLE);
            rvRecord.setVisibility(View.GONE);
        }

        // 隐藏空白页，展示列表
        if (mCurrPage == 1 && !ListUtil.isListEmpty(list)) {
            llRecordEmpty.setVisibility(View.GONE);
            rvRecord.setVisibility(View.VISIBLE);
        }

        // 没有更多了
        if (mCurrPage > 1 && ListUtil.isListEmpty(list)) {
            rvRecord.setNoMore(true);
        }

        // 根据当时是否为第一页，来决定是在尾部插入还是直接更新
        recordAdapter.update(list, mCurrPage == 1);

    }

    @Override
    public void onRefresh() {
        mCurrPage = 1;
        mPresenter.getGrowUpRecordList(babyId, mCurrPage);
    }

    @Override
    public void onLoadMore() {
        mCurrPage++;
        mPresenter.getGrowUpRecordList(babyId, mCurrPage);
    }

    @OnClick({R.id.tv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_add:
                // 跳转新增页面
                Bundle bundle = new Bundle();
                bundle.putString(ACT_AddGrowRecord.KEY_BABY_ID, StringUtil.get(babyId));
                readyGo(ACT_AddGrowRecord.class, bundle);
                break;
        }
    }

    /**
     * 弹窗提示编辑当前条目
     *
     * @param item
     */
    private void showAlertToModifyItem(final GrowUpRecordEntity.ListBean item) {
        modifyItemDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_modify_record)
                .setWidthAndHeight(ScreenUtil.dip2px(mContext, 300), ViewGroup.LayoutParams.WRAP_CONTENT)
                .create();

        modifyItemDialog.setOnClickListener(R.id.tv_modify, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 跳转新增页面
                Bundle bundle = new Bundle();
                bundle.putString(ACT_AddGrowRecord.KEY_BABY_WEIGHT, StringUtil.get(item.getWeight()));
                bundle.putString(ACT_AddGrowRecord.KEY_BABY_HEIGHT, StringUtil.get(item.getHeight()));
                bundle.putString(ACT_AddGrowRecord.KEY_BABY_ITEM_ID, StringUtil.get(item.getId()));

//                String babyDate = "";
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
//                try {
//                    Date date = simpleDateFormat.parse(item.getDate());
//                    babyDate = StringUtil.get(date.getTime());
//                } catch (ParseException e) {
//                    e.printStackTrace();
//                }

                bundle.putString(ACT_AddGrowRecord.KEY_BABY_DATE, StringUtil.get(item.getDate()));
                bundle.putString(ACT_AddGrowRecord.KEY_BABY_ID, StringUtil.get(babyId));
                readyGo(ACT_AddGrowRecord.class, bundle);

                modifyItemDialog.dismiss();
            }
        });

        modifyItemDialog.setOnClickListener(R.id.tv_delete, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 删除记录
                showAlertToAlertDelete(item.getId());

            }
        });

        modifyItemDialog.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                modifyItemDialog.dismiss();
            }
        });

        modifyItemDialog.show();
    }

    @Override
    public void deleteItemSucceed() {
        modifyItemDialog.dismiss();
        ToastUtil.makeText(mContext, "删除成功", false);

        recordAdapter.updateDeleteForXRV(modifyItemPos);
        modifyItemPos = -1;

        // 展示空页面
        if (ListUtil.isListEmpty(recordAdapter.getDatas())) {
            llRecordEmpty.setVisibility(View.VISIBLE);
            rvRecord.setVisibility(View.GONE);
        }

    }

    /**
     * 弹窗提示删除后不可撤销
     *
     * @param itemId
     */
    private void showAlertToAlertDelete(final String itemId) {
        final AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                .setContentView(R.layout.dialog_alert_delete)
                .setWidthAndHeight(ScreenUtil.dip2px(mContext, 300), ScreenUtil.dip2px(mContext, 180))
                .create();

        alertDialog.setOnClickListener(R.id.tv_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPresenter.doDeleteCurrItem(babyId, itemId);
                alertDialog.dismiss();
            }
        });

        alertDialog.setOnClickListener(R.id.tv_cancel, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        alertDialog.show();
    }

}
